package com.ruoyi.consumer.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.consumer.domain.PaymentRecord;
import com.ruoyi.consumer.enums.PaymentStatusEnums;
import com.ruoyi.consumer.mapper.PaymentRecordMapper;
import com.ruoyi.consumer.service.IPaymentRecordService;
import com.ruoyi.consumer.util.WechatPayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * 微信支付记录Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-08
 */
@Service
public class PaymentRecordServiceImpl implements IPaymentRecordService {

    @Autowired
    private PaymentRecordMapper paymentRecordMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询微信支付记录
     *
     * @param id 微信支付记录主键
     * @return 微信支付记录
     */
    @Override
    public PaymentRecord selectPaymentRecordById(String id) {
        Assert.notNull(id, "支付记录查询编号不能为空！");
        return paymentRecordMapper.selectPaymentRecordById(id);
    }

    /**
     * 查询微信支付记录列表
     *
     * @param paymentRecord 微信支付记录
     * @return 微信支付记录
     */
    @Override
    public List<PaymentRecord> selectPaymentRecordList(PaymentRecord paymentRecord) {
        return paymentRecordMapper.selectPaymentRecordList(paymentRecord);
    }


    /**
     * 删除支付记录
     * 1、删除当前支付记录的表记录
     * 2、删除此计划的redis防止重复标识
     * @param id
     */
    @Override
    public void deletePaymentRecordById(String id) {
        if (StringUtils.isBlank(id)) {
            throw new ServiceException("支付记录编号不能为空！");
        }
        PaymentRecord paymentRecord = paymentRecordMapper.selectPaymentRecordById(id);
        if (paymentRecord == null) {
            throw new ServiceException("查询支付记录为空，删除失败！");
        }

        // 删除记录
        int countNum = paymentRecordMapper.deletePaymentRecordById(id);
        if (countNum != 1) {
            throw new ServiceException("删除支付记录失败！");
        }

        String paymentStatus = paymentRecord.getPaymentStatus();
        if (PaymentStatusEnums.SUCCESS.name().equals(paymentStatus)) {
            // 支付成功的记录删除redis限制记录
            String planId = paymentRecord.getPlanId();
            redisCache.deleteObject(StrUtil.format(WechatPayUtils.PLAN_ID_PAY_STATUS, planId));
        }

    }
}
